package com.trs.publish.aspect;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.gson.Gson;
import com.trs.publish.Constants.Constants;
import com.trs.publish.domain.OperationLog;

/**
 * @author jiahaihong
 *
 */
@Aspect
@Component
public class OperationAspect {
	
	
	private static final  Logger logger = LoggerFactory.getLogger(OperationAspect.class);

	 /** 
     * Pointcut 
     * 定义Pointcut，Pointcut的名称为annotationPointCut()，此方法没有返回值和参数 
     * 该方法就是一个标识，不进行调用 
     */ 
	@Pointcut("@annotation(com.trs.publish.aspect.OperationDesc)")
	public void annotationPointCut() {}
	
	@Before("annotationPointCut()")
    public void doBefore(JoinPoint joinPoint){
       MethodSignature sign =  (MethodSignature)joinPoint.getSignature();
       Method method = sign.getMethod();
       logger.info("接受方法的"+method.getName()+"前置日志");
    }
	
	
	@After("annotationPointCut()")
	public void doAfter(JoinPoint joinPoint) throws ClassNotFoundException {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		
		MethodSignature sign =  (MethodSignature)joinPoint.getSignature();
	    Method method = sign.getMethod();
		String description = method.getAnnotation(OperationDesc.class).description();  
		//url
		logger.info("url={}", request.getRequestURL());
		//method
		logger.info("method={}",request.getMethod());
		//ip
		logger.info("ip={}",request.getRemoteAddr());
		//类方法
		logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
		//参数
		logger.info("args={}",joinPoint.getArgs());
		OperationLog log = new OperationLog();
		log.setIp(request.getRemoteAddr());
		String params="";
		Gson gson = new Gson();
		if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {  
         	params = gson.toJson(joinPoint.getArgs());
        }
		log.setMethodparams(params);
        Constants.operationLogQueue.offer(log);
		
	}
    
}
